<template>
  <div class="user-list">
    <el-card>
      <template #header>
        <div class="card-header">
          <span class="card-title">用户管理</span>
        </div>
      </template>
      
      <DataTable
        :data="tableData"
        :columns="columns"
        :loading="loading"
        :search-fields="searchFields"
        :total="total"
        :current-page="currentPage"
        :page-size="pageSize"
        @add="handleAdd"
        @edit="handleEdit"
        @delete="handleDelete"
        @batch-delete="handleBatchDelete"
        @search="handleSearch"
        @refresh="handleRefresh"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      >
        <template #status="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'danger'" size="small">
            {{ row.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </template>
        
        <template #avatar="{ row }">
          <el-avatar :size="32" :src="row.avatar">
            {{ row.name.charAt(0) }}
          </el-avatar>
        </template>
        
        <template #roles="{ row }">
          <el-tag
            v-for="role in row.roles"
            :key="role"
            size="small"
            style="margin-right: 4px"
          >
            {{ role }}
          </el-tag>
        </template>
        
        <template #row-actions="{ row }">
          <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
          <el-button type="warning" link @click="handleResetPassword(row)">重置密码</el-button>
          <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
        </template>
      </DataTable>
    </el-card>
    
    <!-- 用户表单对话框 -->
    <FormDialog
      v-model="showDialog"
      :title="dialogTitle"
      :fields="formFields"
      :data="currentUser"
      :loading="submitLoading"
      @submit="handleSubmit"
      @close="handleDialogClose"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import DataTable from '@/components/DataTable.vue'
import FormDialog from '@/components/FormDialog.vue'
import type { TableColumn, SearchField } from '@/components/DataTable.vue'
import type { FormField } from '@/components/FormDialog.vue'

// 表格数据
const tableData = ref<any[]>([])
const loading = ref(false)
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(20)

// 对话框状态
const showDialog = ref(false)
const dialogTitle = ref('')
const currentUser = ref<any>({})
const submitLoading = ref(false)

// 表格列配置
const columns: TableColumn[] = [
  { prop: 'id', label: 'ID', width: 80, sortable: true },
  { prop: 'avatar', label: '头像', width: 80, slot: 'avatar' },
  { prop: 'username', label: '用户名', minWidth: 120 },
  { prop: 'name', label: '姓名', minWidth: 120 },
  { prop: 'email', label: '邮箱', minWidth: 180 },
  { prop: 'phone', label: '手机号', minWidth: 120 },
  { prop: 'roles', label: '角色', minWidth: 120, slot: 'roles' },
  { prop: 'status', label: '状态', width: 80, slot: 'status' },
  { prop: 'createdAt', label: '创建时间', width: 160, sortable: true },
  { prop: 'lastLoginAt', label: '最后登录', width: 160 }
]

// 搜索字段配置
const searchFields: SearchField[] = [
  { prop: 'keyword', label: '关键词', type: 'input' },
  {
    prop: 'status',
    label: '状态',
    type: 'select',
    options: [
      { label: '启用', value: 1 },
      { label: '禁用', value: 0 }
    ]
  },
  {
    prop: 'role',
    label: '角色',
    type: 'select',
    options: [
      { label: '管理员', value: 'admin' },
      { label: '用户', value: 'user' }
    ]
  }
]

// 表单字段配置
const formFields: FormField[] = [
  { prop: 'username', label: '用户名', type: 'input', required: true },
  { prop: 'name', label: '姓名', type: 'input', required: true },
  { prop: 'email', label: '邮箱', type: 'input', required: true },
  { prop: 'phone', label: '手机号', type: 'input' },
  {
    prop: 'roles',
    label: '角色',
    type: 'checkbox',
    required: true,
    options: [
      { label: '管理员', value: 'admin' },
      { label: '用户', value: 'user' },
      { label: '编辑', value: 'editor' }
    ]
  },
  {
    prop: 'status',
    label: '状态',
    type: 'radio',
    required: true,
    options: [
      { label: '启用', value: 1 },
      { label: '禁用', value: 0 }
    ]
  },
  { prop: 'remark', label: '备注', type: 'textarea' }
]

// 模拟数据
const mockUsers = [
  {
    id: 1,
    username: 'admin',
    name: '管理员',
    email: 'admin@example.com',
    phone: '13800138000',
    avatar: '',
    roles: ['admin'],
    status: 1,
    createdAt: '2024-01-01 10:00:00',
    lastLoginAt: '2024-01-15 09:30:00',
    remark: '系统管理员'
  },
  {
    id: 2,
    username: 'user001',
    name: '张三',
    email: 'zhangsan@example.com',
    phone: '13800138001',
    avatar: '',
    roles: ['user'],
    status: 1,
    createdAt: '2024-01-02 14:20:00',
    lastLoginAt: '2024-01-14 16:45:00',
    remark: '普通用户'
  },
  {
    id: 3,
    username: 'editor001',
    name: '李四',
    email: 'lisi@example.com',
    phone: '13800138002',
    avatar: '',
    roles: ['editor', 'user'],
    status: 1,
    createdAt: '2024-01-03 11:15:00',
    lastLoginAt: '2024-01-13 08:20:00',
    remark: '内容编辑'
  },
  {
    id: 4,
    username: 'user002',
    name: '王五',
    email: 'wangwu@example.com',
    phone: '13800138003',
    avatar: '',
    roles: ['user'],
    status: 0,
    createdAt: '2024-01-04 16:30:00',
    lastLoginAt: '2024-01-10 12:10:00',
    remark: '已禁用用户'
  }
]

// 获取用户列表
const fetchUsers = async (params: any = {}) => {
  loading.value = true
  try {
    // 模拟 API 调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    let filteredData = [...mockUsers]
    
    // 模拟搜索过滤
    if (params.keyword) {
      filteredData = filteredData.filter(user =>
        user.username.includes(params.keyword) ||
        user.name.includes(params.keyword) ||
        user.email.includes(params.keyword)
      )
    }
    
    if (params.status !== undefined && params.status !== '') {
      filteredData = filteredData.filter(user => user.status === params.status)
    }
    
    if (params.role) {
      filteredData = filteredData.filter(user => user.roles.includes(params.role))
    }
    
    total.value = filteredData.length
    
    // 模拟分页
    const start = (currentPage.value - 1) * pageSize.value
    const end = start + pageSize.value
    tableData.value = filteredData.slice(start, end)
  } catch (error) {
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 处理新增
const handleAdd = () => {
  dialogTitle.value = '新增用户'
  currentUser.value = {}
  showDialog.value = true
}

// 处理编辑
const handleEdit = (row: any) => {
  dialogTitle.value = '编辑用户'
  currentUser.value = { ...row }
  showDialog.value = true
}

// 处理删除
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm(`确定要删除用户 "${row.name}" 吗？`, '确认删除', {
      type: 'warning'
    })
    
    ElMessage.success('删除成功')
    fetchUsers()
  } catch (error) {
    // 用户取消删除
  }
}

// 处理批量删除
const handleBatchDelete = async (rows: any[]) => {
  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${rows.length} 个用户吗？`, '确认批量删除', {
      type: 'warning'
    })
    
    ElMessage.success('批量删除成功')
    fetchUsers()
  } catch (error) {
    // 用户取消删除
  }
}

// 处理重置密码
const handleResetPassword = async (row: any) => {
  try {
    await ElMessageBox.confirm(`确定要重置用户 "${row.name}" 的密码吗？`, '确认重置密码', {
      type: 'warning'
    })
    
    ElMessage.success('密码重置成功，新密码已发送到用户邮箱')
  } catch (error) {
    // 用户取消操作
  }
}

// 处理搜索
const handleSearch = (params: any) => {
  currentPage.value = 1
  fetchUsers(params)
}

// 处理刷新
const handleRefresh = () => {
  fetchUsers()
}

// 处理分页大小变化
const handleSizeChange = (size: number) => {
  pageSize.value = size
  fetchUsers()
}

// 处理当前页变化
const handleCurrentChange = (page: number) => {
  currentPage.value = page
  fetchUsers()
}

// 处理表单提交
const handleSubmit = async (data: any) => {
  submitLoading.value = true
  try {
    // 模拟 API 调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success(currentUser.value.id ? '更新成功' : '创建成功')
    showDialog.value = false
    fetchUsers()
  } catch (error) {
    ElMessage.error('操作失败')
  } finally {
    submitLoading.value = false
  }
}

// 处理对话框关闭
const handleDialogClose = () => {
  currentUser.value = {}
}

onMounted(() => {
  fetchUsers()
})
</script>

<style lang="scss" scoped>
.user-list {
  .card-title {
    font-size: 18px;
    font-weight: 600;
    color: #2c3e50;
  }
}
</style>
